
export class CollaborationSocket {
  constructor(url, roomId, userId, msgType) {
    this.url = url
    this.roomId = roomId
    this.userId = userId
    this.msgType = msgType
    this.socket = null
    this.messageHandlers = {
      'chat': [],
      'mind': [],
      'file': []
    }
  }

  connect() {
    this.socket = new WebSocket(`${this.url}/ws/${this.roomId}/${this.userId}`)

    this.socket.onopen = () => {
      console.log('WebSocket connected')
    }

    this.socket.onmessage = (event) => {
      const message = JSON.parse(event.data)
      const handlers = this.messageHandlers[message.type] || []
      handlers.forEach(handler => handler(message))
    }

    this.socket.onclose = () => {
      console.log('WebSocket disconnected')
    }
  }

  disconnect() {
    if (this.socket) {
      this.socket.close()
    }
  }

  on(type, handler) {
    if (!this.messageHandlers[type]) {
      this.messageHandlers[type] = []
    }
    this.messageHandlers[type].push(handler)
  }

  sendMindmapUpdate(content) {
    this._send({
      type: '1',
      content
    })
  }

  sendChatMessage(text, username) {
    this._send({
      type: '0',
      text,
      username
    })
  }

  _send(message) {
    if (this.socket && this.socket.readyState === WebSocket.OPEN) {
      this.socket.send(JSON.stringify(message))
    }
  }
}